import { getAuthToken, setAuthToken, clearAuthToken, getUserInfo } from '@/utils/auth'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    isLoggedIn: !!getAuthToken(),
    token: getAuthToken() || '',
    username: localStorage.getItem('username') || '',
    userId: localStorage.getItem('userId') || '',
    permissions: (() => {
      const stored = localStorage.getItem('permissions')
      try {
        return stored ? JSON.parse(stored) : ['USER']
      } catch (e) {
        return stored ? stored.split(',') : ['USER']
      }
    })()
  }),

  actions: {
    // 登录成功后调用
    loginSuccess(payload) {
      this.token = payload.token
      this.username = payload.username
      this.userId = payload.userId
      this.permissions = payload.permissions || ['USER']
      this.isLoggedIn = true

      setAuthToken(payload.token)
      localStorage.setItem('username', payload.username)
      localStorage.setItem('userId', payload.userId)
      localStorage.setItem('permissions', JSON.stringify(payload.permissions || ['USER']))
    },

    // 登出
    logout() {
      this.token = ''
      this.username = ''
      this.userId = ''
      this.permissions = ['USER']
      this.isLoggedIn = false

      clearAuthToken()
      localStorage.removeItem('username')
      localStorage.removeItem('userId')
      localStorage.removeItem('permissions')
    },

    // 路由守卫中刷新 token
    async refreshToken() {
const tk = getAuthToken()
      this.token = tk || ''
      if (tk) {
        // 同步到 service
        setAuthToken(tk)
      }
      // 如果已经 loginSuccess 过，用户名／权限就不用再拉了
      return this.token
},


    // 根据 token 获取用户信息
    async fetchUser() {
      try {
        const res = await getUserInfo()
        if (res.data.code !== 0) throw new Error('用户信息获取失败')

        const user = res.data.data
        this.username = user.username
        this.userId = user.userId
        this.permissions = user.permissions || ['USER']
        this.isLoggedIn = true

        localStorage.setItem('username', user.username)
        localStorage.setItem('userId', user.userId)
        localStorage.setItem('permissions', JSON.stringify(user.permissions || ['USER']))

        return true
      } catch (err) {
        this.logout()
        return false
      }
    }
  }
})
